#include "ChatBroadcast.hh"
#include "XmlClient.hh"
#include "../Exception.hh"

using namespace Network;

spChatBroadcast ChatBroadcast::construct(QDomElement const& message) {

    QDomElement sender = message.firstChildElement("sender");
    QDomNode senderText = sender.firstChild();
    QDomElement msg = message.firstChildElement("message");
    QDomNode msgText = msg.firstChild();

    if (!(sender.isElement() && senderText.isText()))
            throw NonFatalProtocolError(
            		"chat_broadcast.message missing or invalid");

    if (!(msg.isElement() && msgText.isText()))
            throw NonFatalProtocolError(
            		"chat_broadcast.message missing or invalid");

    return spChatBroadcast(new ChatBroadcast(
    		senderText.toText().nodeValue(), msgText.toText().nodeValue()));
}

ChatBroadcast::ChatBroadcast(QString const& sender, QString const& msg):
		sender(sender),
		msg(msg)
{
}

void ChatBroadcast::process_on_client(XmlClient& client)
{
	client.chat_msg_received(sender, msg);
}

QDomDocument ChatBroadcast::to_xml() const {
    QDomDocument doc;
    QDomElement chat = doc.createElement("chat_broadcast");
    QDomElement msgElem = doc.createElement("message");
    QDomText msgText = doc.createTextNode(msg);
    QDomElement senderElem = doc.createElement("sender");
    QDomText senderText = doc.createTextNode(sender);
    doc.appendChild(chat);
    chat.appendChild(msgElem);
    msgElem.appendChild(msgText);
    chat.appendChild(senderElem);
    senderElem.appendChild(senderText);
    return doc;
}
